//tiny portal jquery plugin
(
function($)
{
	var TinyPortal = {
		dependencies :new Array(),
		currentDependencies :new Array(),
		
		debug : function(str) {
			if (str) {
				var debugDiv = $("#ajaxconsole").css('color','red');
				if (debugDiv != null) {
					debugDiv.html(debugDiv.html()+str);
				}
			}
		},

		formData : function(form) {
			this.urlEncode = function(string) {
				string = string.replace(/ /g, '+');
				return escape(string);
			};

			this.toString = function() {
				var r = '';
				for ( var field in this.fields)
					r += field + ': ' + this.fields[field] + '\n';
				return r;
			};

			this.toQueryString = function() {
				var r = '';
				for ( var field in this.fields)
					if (typeof this.fields[field] != 'string')
						for ( var i = 0; i < this.fields[field].length; i++)
							r += this.urlEncode(field) + '='
									+ this.urlEncode(this.fields[field][i]) + '&';
					else
						r += this.urlEncode(field) + '='
								+ this.urlEncode(this.fields[field]) + '&';
				r = r.substring(0, r.length - 1);
				return r;
			};

			var fields = this.fields = new Object();
			var submitButtonProcessed = false;
			if (form.submitButtonName) {
				fields[form.submitButtonName] = "true";
				submitButtonProcessed = true;
			}
			for ( var e = 0; e < form.elements.length; e++) {
				var field = form.elements[e];
				if (field.name) {
					if ((field.type.toLowerCase() == 'text'
							|| field.type.toLowerCase() == 'textarea'
							|| field.type.toLowerCase() == 'password'
							|| field.type.toLowerCase() == 'hidden' || field.type
							.toLowerCase() == 'file')
							&& field.value)
						fields[field.name] = field.value;
					else if ((field.type.toLowerCase() == 'checkbox' || field.type
							.toLowerCase() == 'radio')
							&& field.checked)
						fields[field.name] = field.value;
					else if (field.type.toLowerCase() == 'select-one'
							&& field.selectedIndex != -1)
						fields[field.name] = field.options[field.selectedIndex].value;
					else if (field.type.toLowerCase() == 'select-multiple'
							&& field.selectedIndex != -1) {
						fields[field.name] = new Array();
						for ( var i = 0; i < field.options.length; i++)
							if (field.options[i].selected)
								fields[field.name][fields[field.name].length] = field.options[i].value;
					} else if (!submitButtonProcessed
							&& field.type.toLowerCase() == 'submit' && field.name) {
						fields[field.name] = "1";
						submitButtonProcessed = true;
					}
				}
			}
		},

	    getXHR : function() {
	        var xmlReq = null;
	        if (window.XMLHttpRequest) xmlReq = new XMLHttpRequest();
	        if (xmlReq == null && window.ActiveXObject) {
	            xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
	            if (xmlReq == null) xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
	        }
	        return xmlReq;
	    },
	    
		xhReq : function(target, params, callback, method) {
	    	function ajaxBindCallback(){
	            if (ajaxRequest.readyState == 4) {
	                if (ajaxRequest.status == 200) {
	                    if (ajaxCallback){
	                        ajaxCallback(ajaxRequest);
	                    } else {
	                        alert('no callback defined');
	                    }
	                } else {
	                    alert("There was a problem retrieving the xml data:\n" +
	                    ajaxRequest.status + ":\t" +
	                    ajaxRequest.statusText + "\n" + ajaxRequest.responseText);
	                }
	            }
	        }

	        var ajaxRequest = null;
	        var ajaxCallback = callback;

	        ajaxRequest = TinyPortal.getXHR();

	        if (ajaxRequest == null) return true;

	        if (method == "get"&&params != null) {
	            target += (target.indexOf("?") < 0 ? "?" : "&") + params;
	            params = null;
	        }

	        ajaxRequest.onreadystatechange = ajaxBindCallback;
	        ajaxRequest.open(method, target, true);
	        if (method == "post") {
	            ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	        }
	        ajaxRequest.send(params);

	        TinyPortal.debug("Ajax request sent to: " + target + "<br/>");

	        // On success return false to prevent submitting form in regular fashion.
	        return false;
		},
		
		handleResponse : function(xhr) {
			TinyPortal.debug("Ajax response received" + "<br/>");
			var doc = xhr.responseXML;
			var source = doc.getElementsByTagName("div")[0];
			var id = source.getAttribute("id");
			var defPos = id.indexOf("_tp", 0);
			if (defPos > 0) {
				id = id.substring(0, defPos);
			}
			var target = $('#'+id);
			if (target != null) {
				TinyPortal.debug("Target for id " + id + " found" + "<br/>");
				target.html(xhr.responseText);
				TinyPortal.apply();
			}

			var dep = TinyPortal.currentDependencies.pop();
			while(dep != null) {
				TinyPortal.debug("Next in queue: " + dep + "<br/>");
				TinyPortal.xhReq(dep, null,TinyPortal.handleResponse, "get");
				dep = TinyPortal.currentDependencies.pop();
			}
		},

		loadPortlet : function(el) {
			TinyPortal.debug("<br/>");
			var url = null;
			var params = null;
			var method = 'post';

			if (el.href) {
				url = el.href;
			} else if (el.action) {
				if (el.method)
					method = el.method;
				url = el.action;
				var fd = new this.formData(el);
				if (fd) {
					params = fd.toQueryString();
				}
			} else {
				return false;
			}

			if (TinyPortal.dependencies) {
				TinyPortal.debug("There are dependants <br/>");
				for (selector in TinyPortal.dependencies) {
					TinyPortal.debug("Dependant: "
							+ TinyPortal.dependencies[selector] + " from "
							+ selector + "<br/>");
					if (url.indexOf(selector) > -1) {
						TinyPortal.debug("Dependant found: "
								+ TinyPortal.dependencies[selector] + " <br/>");
						TinyPortal.currentDependencies = new Array();
						var depArray = TinyPortal.dependencies[selector];
						if (depArray && depArray.length > 0) {
							TinyPortal.currentDependencies = new Array();
							for (var loop = 0; loop < depArray.length; loop++) {
								TinyPortal.currentDependencies[loop] = depArray[loop];
							}
						}
					}
				}
			}
			return TinyPortal.xhReq(url, params,TinyPortal.handleResponse, method);
		},
		apply : function() {
			$('.portlet a').bind('click',function(e){return TinyPortal.loadPortlet(this);});
			$('a.portlet').bind('click',function(e){return TinyPortal.loadPortlet(this);});
			$('.portlet form').bind('submit',function(e){return TinyPortal.loadPortlet(this);});
			$('form.portlet').bind('submit',function(e){return TinyPortal.loadPortlet(this);});
			$('.portlet input').bind('click',function(e){
				if( this.form && this.type.toLowerCase() == 'submit') {this.form.submitButtonName=this.name;};return true;
			});
			$('input.portlet').bind('click',function(e){
				if( this.form && this.type.toLowerCase() == 'submit') {this.form.submitButtonName=this.name;};return true;
			});
		},
		start : function() {
			$(window).bind('load',function() {TinyPortal.apply(); }
			);
		}
	};
	
	$.registerDependencies = function(ch) {
		TinyPortal.dependencies = ch;
	};
	
	$.startTinyPortal = function() {
		TinyPortal.start();
	}
}
)(jQuery);

jQuery.startTinyPortal();